#include "TcpServer.hpp"
#include "Calculator.hpp"
#include "TcpServer.hpp"

using cal_fun = function<Response(const Request& req)>;
class Parse
{
public:
    Parse(cal_fun cal)
        :_cal(cal)
    {}
    ~Parse()
    {}

    string Entry(string& package)
    {
        string message;
        string respstr;   
        //1.判断报文的完整性
        while(Decode(package,&message))
        {
            LOG(LogGrade::NORMAL) << "Content:\n" << message;
            if(message.empty())
                break;
            //2. 反序列化  message 曾经被序列化过了
            Request req;
            if(!req.DeSerialize(message))
            {
                LOG(LogGrade::ERROR) << "反序列化失败";
                break;
            }

            cout << "===============" << endl;
            req.Print();
            cout << "===============" << endl;

            //3. 计算结果
            Response res = _cal(req);

            //4 .序列化
            string tmp;
            res.Serialize(tmp);
            LOG(LogGrade::NORMAL) << tmp;

            //5. 添加长度报头
            Encode(tmp);
            LOG(LogGrade::NORMAL) << tmp;
            //6. 拼接应答（一条报文中有多条计算）
            respstr += tmp;
        }
        return respstr; //报文不完整，直接返回空串
    }
private:
    cal_fun _cal;
};


int main()
{
    ENABLE_CONSOLE_LOG_STRATEGY();
    //7 应用层处理对象
    Calculator cal;
    //6 表示层
    Parse myparse([&cal](const Request& req)->Response{
        return cal.Execute(req);
    });
    //5 会话层
    unique_ptr<tcpServer> tcps = make_unique<tcpServer>([&myparse](string& package){
        return myparse.Entry(package);
    });

    tcps->Init();
    tcps->Start();
    return 0;
}